import { routeMapping, router } from "@/router/index";
import { store, storeCommitPath } from "@/store/index";
import APIConst from "@/common/constants/APIConst";
import { APIResponse } from "@/common/model/APIResponse";
import { HttpClient } from "@/axios/HttpClient";
// import MMService from "@/common/services/MMService";
// import SweetAlertService from "@/common/services/SweetAlertService";
import SysMsgService from "@/common/services/SysMsgService";

const AuthenticateService = {
  async Login(
    compCode: string,
    userName: string,
    password: string,
    rememberMe: boolean
  ) {
    const reqObj = {
      compCode: compCode,
      username: userName,
      password: password,
    };

    // await store.commit(storeCommitPath.setDisplayPopup, false);
    const Response = await HttpClient.post<APIResponse>(
      APIConst.authentication.login,
      reqObj
    );
    const data = Response.data;

    if (data.IsSuccess) {
      store.commit(storeCommitPath.AuthenticationStore.setUserData, data.Data);
      store.commit(
        storeCommitPath.AuthenticationStore.setRememberMe,
        rememberMe
      );
      SysMsgService.getSysMsgTable(store.state.compCode, store.state.Lang);
      await this.getMenuAndSec();

      // await DropDownService.GetEntity();
      // const entNum = store.getters[storeGetterPath.AuthenticationStore.EntNum];
      // const entities = store.getters[storeGetterPath.DropDownStore.entities];
      // const findUser = entities.find((item: any) => item.EntNum == entNum);
      // const result = findUser ? findUser.Contractor : false;
      // store.commit(storeCommitPath.AuthenticationStore.setIsContractor, result);
      store.commit(storeCommitPath.AuthenticationStore.setIsLoggedIn, true);
    }
    return Promise.resolve(data.IsSuccess);
  },
  logout() {
    store.commit(storeCommitPath.AuthenticationStore.removeUserData);
    router.push({ name: routeMapping.Login });
  },
  async reauthenticateToken() {
    console.log("reauthenticateToken");
  },
  async getMenuAndSec() {
    const Response = await HttpClient.post<APIResponse>(
      APIConst.authentication.refreshmenu
    );
    const data = Response.data;
    if (data.IsSuccess) {
      store.commit(storeCommitPath.AuthenticationStore.setMenu, data.Data);
    }
    return Promise.resolve(data.IsSuccess);
  },
};
export default AuthenticateService;
